from .models import Banner
from .serializer import BannerModelSerializer
from django.core.cache import cache
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin
from rest_framework.response import Response
from django.conf import settings


from utils import time

class BannerView(GenericViewSet, ListModelMixin):
    """首页轮播图视图接口"""
    queryset = Banner.objects.filter(is_delete=False, is_show=True).order_by('orders')[:settings.BANNER_COUNTER]
    serializer_class = BannerModelSerializer

    # 把data的数据加到缓存
    # 1. 先去缓存拿数据库
    # def list(self, request, *args, **kwargs):
    #     banner_list = cache.get('banner_list')
    #     # banner_update.delay()
    #     if not banner_list:
    #         # print('走数据库了')
    #         # 缓存中没有，去数据库拿
    #         respnose = super().list(request, *args, **kwargs)
    #
    #         cache.set('banner_list', respnose.data, 60 * 60 * 24)
    #         return respnose
    #
    #     return Response(data=banner_list)

    def list(self, request, *args, **kwargs):
        banner_key = settings.BANNER_KEY
        response_data = cache.get(banner_key)
        if not response_data:
            response = super().list(request, *args, **kwargs)

            cache.set(banner_key, response.data, time())
            return response
        return Response(response_data)